前端学习笔记 React (2) 组件,Render,Props

每一个独立或者可重复的部分, 都可以单独定义成一个组件.

Comment.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react';

class Comment extends React.Component {
render() {
return (
<div className="ui comments">
<div className="content">
<span className="author">{this.props.author}</span>
<div className="metadata">
<span className="date">{this.props.date}</span>
</div>
<div className="text">{this.props.children}</span>
</div>
</div>
);
}
}

export { Comment as default };

CommentList.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from "react";
import Comment from "./Comment.js";

class CommentList extends React.Component {
render() {
return (
<div>
<Comment author="OnO" date="2018-06-22">
评论内容1
</Comment>
<Comment author="OnO" date="2018-06-27">
评论内容2
</Comment>
</div>
);
}
}

index.html

1
2
3
<!-- ... -->
<div id="app"></div>
<!-- ... -->

main.js

1
2
3
4
5
6
import "semantic-ui/semantic.min.css!";
import React from "react";
import ReactDOM from "react-dom";
import CommentList from "./CommentList.js";

ReactDOM.render(<CommentList />, document.getElementById("app"));

其中 props 对象的键值在 <> 内的部分直接传递, props.children 参数为<> </> 之间的内容.

上面手工的进行了静态数据的传递, 那么下面进行动态数据传递.

main.js

1
2
3
4
5
6
7
8
const comments = [
{ author: "OnO", date: "2018-06-28", text: "评论内容1" },
{ author: "OnO", date: "2018-06-29", text: "评论内容2" },
];

// ...
<CommentList data={comments} />;
// ...

CommentList.js

1
2
3
4
5
6
7
8
9
10
11
render() {
const commentNodes = this.props.data.map(comment => {
return (
<Comment author={comment.author} date={comment.date}>{comment.text}</Comment>
);
});

return (
<div>{commontNodes}</div>
);
}

服务器获取静态数据:

main.js

1
2
3
const commentsUrl = "app/comments.json";

<CommentList data={commentsUrl} />;
Donate - Support to make this site better.
捐助 - 支持我让我做得更好.